package com.umakr.ax.security.service;

import com.umakr.ax.security.core.ano.AccessByRole;
import com.umakr.ax.security.core.ano.AccessByUser;
import com.umakr.ax.security.core.ano.AccessType;
import com.umakr.ax.security.core.ano.IgnoreSec;
import com.umakr.ax.security.model.Res;
import com.umakr.ax.security.mapper.ResMapper;
import com.umakr.ax.core.base.BaseService;
import com.umakr.ax.utils.WebUtil;
import com.google.common.collect.Lists;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;

/**
 * <p>
 * 资源 服务实现类
 * </p>
 *
 * @author gx
 * @since 2017-04-25
 */
@Service
public class ResService extends BaseService<ResMapper, Res>{

    /**
     * 扫描Controller中的方法的注解,获取特定访问权限。
     * @since 2017/4/25 16:19
     */
    public List<String> method(final AccessType type){
        RequestMappingHandlerMapping requestMappingHandlerMapping = WebUtil.getBean(RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = requestMappingHandlerMapping.getHandlerMethods();
        List<String> sResList = Lists.newArrayList();
        if(handlerMethods != null){
            handlerMethods.forEach(new BiConsumer<RequestMappingInfo,HandlerMethod>(){
                @Override
                public void accept(RequestMappingInfo requestMappingInfo, HandlerMethod handlerMethod) {
                    Object obj  = null;
                    switch (type){
                        case ACCESS_BY_ROLE_USER:
                            obj  = handlerMethod.getMethodAnnotation(AccessByUser.class);
                            break;
                        case ACCESS_BY_ROLE_NAME:
                            obj  = handlerMethod.getMethodAnnotation(AccessByRole.class);
                            break;
                        case ACCESS_BY_IGNORE:
                            obj  = handlerMethod.getMethodAnnotation(IgnoreSec.class);
                            break;
                        default:
                    }
                    if(obj!=null){
                        for (String pattern : requestMappingInfo.getPatternsCondition().getPatterns()) {
                            sResList.add(pattern);
                        }
                    }
                }
            });
        }
        return sResList;
    }
}
